package com.example.recycler.newviewpager;

import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {
    private RelativeLayout mActivityMain;
    private ViewPager mVp;
    private int[] mImageViews={R.drawable.vp3,R.drawable.vp1,R.drawable.vp2,R.drawable.vp3,R.drawable.vp1};
    private MyAdapter mAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mActivityMain = (RelativeLayout) findViewById(R.id.activity_main);
        mVp = (ViewPager) findViewById(R.id.vp);
        mAdapter=new MyAdapter();
        mVp.setAdapter(mAdapter);
        //设置刚上来加载的条目是1？
        mVp.setCurrentItem(1);
        mVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position==4) {
                    mVp.setCurrentItem(1,false);
                }
                if (position==0) {
                    mVp.setCurrentItem(3,false);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }
    class MyAdapter extends PagerAdapter{

        @Override
        public int getCount() {
            return mImageViews.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view==object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView=new ImageView(MainActivity.this);
            imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            imageView.setImageResource(mImageViews[position]);
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            //销毁时，做移除操作？
           container.removeView((View) object);
        }
    }
}
